<template>
	<el-upload class="upload-demo" action="#" :show-file-list="false"
		:before-upload="beforeAvatarUpload" :on-remove="handleRemove" :http-request="uploadOk">
		<span class="upload-btn">导入</span>
	</el-upload>
</template>

<script>
export default{
	props:{
		options: {
			require: true,
			type: Object
		}
	},
	data() {
		return {
	        files: {},												//上传的文件
		};
	},
	methods: {
		/* 文件上传前验证 */
		beforeAvatarUpload(file) {
			console.log(file);
			let Xls = file.name.split('.'); 
			if(Xls[1] === 'xls'||Xls[1] === 'xlsx'){
				return file
			}else {
				this.$message.error('上传文件只能是 xls/xlsx 格式!')
				return false
			}
		},
		/* 文件删除 */
		handleRemove(file, fileList) {
			console.log(file);
			console.log(fileList);
		},
		/* 上传成功 */
		uploadOk(val){
			console.log(val);
			let reader = new FileReader();
			FileReader.prototype.readAsBinaryString = f => {
				let binary = "";
				let data = '';
				let outdata = '';
				reader.onload = (e)=> {
					let bytes = new Uint8Array(reader.result);
					let length = bytes.byteLength;
					for (let i = 0; i < length; i++) {
						binary += String.fromCharCode(bytes[i]);
					}
					let XLSX = require("xlsx");
					data = XLSX.read(binary, {type: "binary"});
					outdata = XLSX.utils.sheet_to_json(data.Sheets[data.SheetNames[0]]);
					this.conversion(outdata);
				}
				reader.readAsArrayBuffer(val.file);
			}
			reader.readAsBinaryString(val.file);
		},
		/* 数据格式转换 */
		conversion(arr){
			console.log(arr);
			let list = [];
			if(arr && arr.length > 0){
				arr.forEach(item => {
					let nav = {};
					nav.businessmanName = item['会员名称'];
					nav.identity = item['身份证号码'];
					nav.projectName = item['项目名称'];
					nav.revenue = item['收入金额'];
					nav.incomeTime = item['收入月份'];
					list.push(nav);
				})
			}
			this.$emit('submitEntry',list);
		}
	}
}
</script>

<style scoped="scoped">
.upload-demo{display: inline-block;}
.upload-btn{padding: 10px 20px;border: 1px solid #000;border-radius: 20px;display: inline-block;margin-right: 20px;color: #000;}
</style>
